package com.situ.mall.interceptor;

import com.situ.mall.pojo.entity.User;
import com.situ.mall.pojo.query.UserQuery;
import com.situ.mall.service.IUserService;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.springframework.util.ObjectUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.Enumeration;

public class LoginInterceptor implements HandlerInterceptor {

    private IUserService userService;

    public LoginInterceptor(IUserService userService) {
        this.userService = userService;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute("user");
        if (ObjectUtils.isEmpty(user)) {
            Cookie[] cookies = request.getCookies();
            Cookie cookie = null;
            for (Cookie c : cookies) {
                String name = c.getName();
                if ("autoLoginPortal".equals(name)) {
                    cookie = c;
                    break;
                }
            }
            if (!ObjectUtils.isEmpty(cookie)) {
                System.out.println("滴答滴答滴答滴答");
                String[] values = cookie.getValue().split("&");
                UserQuery userQuery = new UserQuery();
                userQuery.setAccount(values[0]);
                userQuery.setPassword(values[1]);
                User login = userService.login(userQuery.getAccount(), userQuery.getPassword());
                if (!ObjectUtils.isEmpty(login)) {
                    session.setAttribute("user", login);
                }
            }
        }
        if (user == null) {
            // /page/product/list
            // /page/cart/list
            // /cart/add?returnUri=/page/product/detail?id='+id
            String uri = request.getRequestURI();
            String returnUri = request.getParameter("returnUri");
            if (ObjectUtils.isEmpty(returnUri)) {
                response.sendRedirect("/page/login?returnUri=" + uri);
            } else {
                redirect(request, response);
            }
            return false;
        }

        return true;
    }

    private void redirect(HttpServletRequest request, HttpServletResponse response) throws IOException {
//        String returnUri = request.getParameter("returnUri");
//        //获取当前请求的路径
//        //logger.error("请求类型:"+request.getHeader("X-Requested-With"));
//        response.setHeader("Access-Control-Expose-Headers", "REDIRECT,CONTEXTPATH");
//        //告诉ajax我是重定向
//        response.setHeader("REDIRECT", "REDIRECT");
//        //告诉ajax我重定向的路径
//        String url = "https://xxx.xxx.xxx/";//重定向路径
//        response.setHeader("CONTEXTPATH", "/page/login?returnUri=" + returnUri);
//        response.getWriter().write(1);
//        response.setStatus(HttpServletResponse.SC_FORBIDDEN);

        // 获取 returnUri 参数
        String returnUri = request.getParameter("returnUri");

        // 检查 returnUri 是否已经包含查询参数，以决定使用 ? 还是 &
        String delimiter = returnUri.contains("?") ? "&" : "?";

        // 构建完整的 returnUri，只添加 parentId 和 categoryId 参数
        String parentId = request.getParameter("parentId");
        String categoryId = request.getParameter("categoryId");

        if (parentId != null) {
            returnUri += delimiter + "parentId=" + URLEncoder.encode(parentId, "UTF-8");
            delimiter = "&"; // 后续参数使用 & 连接
        }
        if (categoryId != null) {
            returnUri += delimiter + "categoryId=" + URLEncoder.encode(categoryId, "UTF-8");
        }

        // 设置响应头，告诉客户端这是一个重定向请求
        response.setHeader("Access-Control-Expose-Headers", "REDIRECT,CONTEXTPATH");
        response.setHeader("REDIRECT", "REDIRECT");
        response.setHeader("CONTEXTPATH", "/page/login?returnUri=" + returnUri);
        response.getWriter().write(1);
        response.setStatus(HttpServletResponse.SC_FORBIDDEN);
    }
}

